﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace ZhuXingFamilys.ExportExcel.utils
{
    public static partial class TypeExtension
    {
        /// <summary>
        /// 对象的深拷贝对象。
        /// 注意“T”及其里面的引用类型必须标记为可序列化。
        /// </summary>
        public static T Copy<T>(this T obj)
            where T : class
        {
            using (var ms = new MemoryStream())
            {
                var bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
                bf.Serialize(ms, obj);
                ms.Seek(0, SeekOrigin.Begin);
                T CloneObject = default(T);

                try
                {
                    // 反序列化至另一个对象(即创建了一个原对象的深表副本) 
                    CloneObject = (T)bf.Deserialize(ms);
                }
                catch (Exception ex)
                {

                }

                return CloneObject;
            }
        }


    }
}
